package com.sh.linkedList.doubleLinked;

/**
 * @ClassName DoubleLinkedeListDemo
 * @Description 双链表的增删改查实现
 * @Author yaoqiang
 * @Date 2020/10/29 15:13
 * @Version 1.0
 */
public class DoubleLinkedeListDemo {
    public static void main(String[] args) {
        //创建几个节点
        Node node1 = new  Node(1,"aa");
        Node node2 = new Node(2,"bb");
        Node node3 = new Node(3,"cc");
        Node node4 = new Node(4,"dd");
        //创建一个链表
        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();

        doubleLinkedList.add(node1);
        doubleLinkedList.add(node2);
        doubleLinkedList.add(node3);
        doubleLinkedList.add(node4);
        doubleLinkedList.del(node3);
        doubleLinkedList.update(new  Node(1,"a"));
        doubleLinkedList.list();
    }

}


class DoubleLinkedList {
    private Node head = new Node(0, "");

    public Node getHead() {
        return head;
    }

    ;

    //遍历双向链表
    public void list() {
        if (head.next == null) {
            return;
        }
        Node temp = head.next;
        while (true) {
            if (temp == null) {
                break;
            }
            System.out.println(temp);
            temp = temp.next;
        }
    }

    //添加数据到双向链表最后
    public void add(Node node) {
        Node temp = head;
        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = node;
        node.pre = temp;
    }

    //修改节点
    public void update(Node node){
        if (head.next==null){return;}
        Node temp=head.next;

        while (true){
            if (temp==null){
                break;
            }
            if (temp.no==node.no){
                temp.name=node.name;
            }
            temp=temp.next;
        }
    }
    //删除节点
    public  void del(Node node){
        if (head.next==null){
            return;
        }
        Node temp=head.next;
        while (true){
            if (temp==null){
                break;
            }
            if (temp.no==node.no){
                temp.pre.next=temp.next;
                if (temp.next!=null){
                    temp.next.pre=temp.pre;
                }
                break;
            }

            temp=temp.next;
        }
    }
}

class Node {
    public int no;
    public String name;
    public Node pre;
    public Node next;

    public Node(int no, String name) { this.no = no;this.name = name; }

    @Override
    public String toString() { return "Node{no=" + no + ", name='" + name + '\'' + '}'; }
}


